import CryptoJS from 'crypto-js'
// nonce为1-10000随机数字，IP为真实IP，timestamp为秒级时间戳，key为策略接口产品的secret_key
// string 字段为 "nonce=" + $nonce + "&ip=" + ip + "&timestamp=" + timestamp
function encryptByAES(string, key) {
  let ckey = CryptoJS.enc.Utf8.parse(key)
  let encrypted = CryptoJS.AES.encrypt(string, ckey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.ciphertext.toString() // 返回hex格式的密文
}

// string为密文字段，key为产品secret_key
function decryptByAES(string, key) {
  let returnData = null
  try {
    let ckey = CryptoJS.enc.Utf8.parse(key)
    let ciphertext = CryptoJS.enc.Hex.parse(string)
    let srcs = CryptoJS.enc.Base64.stringify(ciphertext)
    let decrypt = CryptoJS.AES.decrypt(srcs, ckey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    })
    const CryptoJSDecrypt = CryptoJS.enc.Utf8.stringify(decrypt).toString()
    returnData = JSON.parse(CryptoJSDecrypt)
  } catch (err) {
    returnData = CryptoJSDecrypt ? CryptoJSDecrypt : null 
  }
  return returnData
}

export default {
  encryptByAES,
  decryptByAES,
}
